import { chat } from '@/services/swagger/chatController';
import { CloudUploadOutlined, CopyOutlined, LinkOutlined, UserOutlined } from '@ant-design/icons';
import type { BubbleProps } from '@ant-design/x';
import { Attachments, AttachmentsProps, Bubble, Sender, XStream } from '@ant-design/x';
import { Button, Flex, GetProp, GetRef, Space, Switch, theme, Typography } from 'antd';
import markdownit from 'markdown-it';
import React, { useRef, useState } from 'react';

const Chat: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [value, setValue] = useState<string>('');
  const [selectedTag, setSelectedTag] = useState<'tag1' | 'tag2' | null>(null);
  const divRef = useRef<HTMLDivElement>(null);
  const attachmentsRef = useRef<GetRef<typeof Attachments>>(null);
  const senderRef = useRef<GetRef<typeof Sender>>(null);
  const [items, setItems] = useState<GetProp<AttachmentsProps, 'items'>>([]);
  const [useDeepMode, setUseDeepMode] = useState<boolean>(false);
  const { token } = theme.useToken();
  const [content, setContent] = useState<string>('');
  const md = markdownit({ html: true, breaks: true });
  const [currentTextContent, setCurrentTextContent] = useState('');

  // Markdown 渲染函数（同时复制内容）
  const renderMarkdown: BubbleProps['messageRender'] = (content) => {
    // 在这里更新状态，不会导致重复渲染问题
    setCurrentTextContent(content);
    return (
      <div>
        <Typography>
          <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
        </Typography>

        {/* 文件列表 */}
        {items.length > 0 && (
          <Flex vertical gap="middle" style={{ marginTop: '12px' }}>
            {items.map((item) => (
              <Attachments.FileCard key={item.uid} item={item} />
            ))}
          </Flex>
        )}
      </div>
    );
  };

  // 流式响应处理器
  const handleStreamResponse = async (response: Response) => {
    if (!response.ok || !response.body) {
      console.error('❌ 响应无效或 body 为空', response);
      setLoading(false);
      setContent('服务器错误');
      return;
    }

    try {
      for await (const chunk of XStream({
        readableStream: response.body,
      })) {
        setContent((prev) => prev + chunk.data);
      }
      console.log('Stream complete');
    } catch (error) {
      console.error('Error reading stream:', error);
      setContent((prev) => prev + '\n\n【回复中断】');
    } finally {
      setLoading(false);
    }
  };

  // 提交逻辑
  const handleSubmit = () => {
    setLoading(true);
    chat({
      conversationId: '84c13c9a-76d9-4b85-a283-c6360a99429d',
      message: value,
    })
      .then(handleStreamResponse)
      .catch((error) => {
        console.error('Request failed:', error);
        setLoading(false);
        alert('发送失败，请检查网络或服务端是否正常');
      });
    setValue('');
    setItems([]);
  };

  // 粘贴文件时自动上传
  const handlePasteFile = (_: File, files: FileList) => {
    for (const file of files) {
      attachmentsRef.current?.upload(file);
    }
  };

  return (
    <div>
      <Bubble
        typing
        content={content}
        messageRender={renderMarkdown}
        avatar={{ icon: <UserOutlined /> }}
        header="Ant Design X"
        footer={() => (
          <Button
            onClick={() => {
              navigator.clipboard.writeText(currentTextContent).then(
                () => console.log('复制成功'),
                (err) => console.error('复制失败:', err),
              );
            }}
            color="default"
            variant="text"
            size="small"
            icon={<CopyOutlined />}
          />
        )}
      />
      <Flex vertical gap="middle" align="flex-start" ref={divRef}>
        <Space size={token.paddingXXS}>
          <Button
            type={selectedTag === 'tag1' ? 'primary' : 'default'}
            onClick={() => {
              setSelectedTag((prev) => (prev === 'tag1' ? null : 'tag1'));
            }}
          >
            first
          </Button>
          <Button
            type={selectedTag === 'tag2' ? 'primary' : 'default'}
            onClick={() => {
              setSelectedTag((prev) => (prev === 'tag2' ? null : 'tag2'));
            }}
          >
            second
          </Button>
        </Space>
        <Sender
          ref={senderRef}
          prefix={
            <Attachments
              ref={attachmentsRef}
              beforeUpload={() => false}
              items={items}
              onChange={({ fileList }) => setItems(fileList)}
              placeholder={{
                icon: <CloudUploadOutlined />,
                title: 'Upload files',
                description: 'Click or drag files to this area to upload',
              }}
              getDropContainer={() => senderRef.current?.nativeElement}
            >
              <Button type="text" icon={<LinkOutlined />} />
            </Attachments>
          }
          value={value}
          loading={loading}
          onChange={setValue}
          onPasteFile={handlePasteFile}
          onSubmit={handleSubmit}
          onCancel={() => {
            setLoading(false);
            console.log('Cancel sending!');
          }}
          allowSpeech
        />

        <Switch
          checked={useDeepMode}
          onChange={setUseDeepMode}
          checkedChildren="深度"
          unCheckedChildren="通用"
        />
      </Flex>
    </div>
  );
};
export default Chat;
